#!/usr/bin/python
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------------------------------------
# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
# CANN Open Software License Agreement Version 2.0 (the "License").
# Please refer to the License for details. You may not use this file except in compliance with the License.
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
# See LICENSE in the root of the software repository for the full text of the License.
# ----------------------------------------------------------------------------------------------------------

import os
import re
import shutil
import subprocess


def split_str_with_space(input_str: str) -> list:
    result = re.split('\s+', input_str)
    return [element for element in result if element != '']


def get_str_between(input_str: str, sub_str_s: str, sub_str_e: str) -> str:
    pattern = rf'{sub_str_s}(.*?){sub_str_e}'
    result = re.search(pattern, input_str)
    if result:
        return result.group(1)
    return ''


def is_prefix_substring(str_check: str, str_lst: list) -> bool:
    for lst_str in str_lst:
        if str_check.lower().startswith(lst_str.lower()):
            return True
    return False


def copy_file_src_exist(src_file: str, dest_file: str) -> None:
    if not os.path.exists(src_file):
        return
    if not os.path.exists(os.path.dirname(dest_file)):
        os.makedirs(os.path.dirname(dest_file))
    shutil.copy(src_file, dest_file)


def get_section_headers_in_file(file_name: str) -> str:
    return subprocess.run(['readelf', '-SW', file_name], capture_output=True, text=True).stdout


def get_symbols_in_file(file_name: str) -> str:
    return subprocess.run(['readelf', '-sW', file_name], capture_output=True, text=True).stdout


def get_all_section_symbols_in_file(file_name: str) -> str:
    return subprocess.run(['readelf', '-aW', file_name], capture_output=True, text=True).stdout


def get_o_file_from_a_file(file_path: str, file_name: str) -> str:
    return subprocess.run(['ar', 'x', file_path, file_name], capture_output=True)